<template>
  <div class="login-page">
    <div class="login-bg"></div>
    <div class="login-card">
      <h1 class="login-title">用户登录</h1>

      <!-- 登录方式切换标签 -->
      <div class="login-tabs">
        <div
            :class="['tab-item', currentTab === 'password' ? 'active' : '']"
            @click="switchTab('password')"
        >
          密码登录
        </div>
        <div
            :class="['tab-item', currentTab === 'sms' ? 'active' : '']"
            @click="switchTab('sms')"
        >
          手机号登录
        </div>
      </div>

      <el-form
          v-if="currentTab === 'password'"
          :model="form"
          label-width="70px"
          class="login-form"
      >
        <el-form-item label="用户名">
          <el-input v-model="form.username" placeholder="请输入用户名"/>
        </el-form-item>
        <el-form-item label="密码">
          <el-input type="password" v-model="form.password" placeholder="请输入密码"/>
        </el-form-item>
        <el-form-item>
          <el-button type="text" @click="$router.push('/registered')">注册</el-button>
          <el-button type="primary" style="margin-left: 10px;" @click="login">登录</el-button>
        </el-form-item>
      </el-form>

      <!-- 手机号验证码登录表单 -->
      <el-form
          v-else
          :model="smsForm"
          label-width="70px"
          class="login-form"
      >
        <el-form-item label="手机号">
          <el-input
              v-model="smsForm.mobile"
              placeholder="请输入手机号"
              maxlength="11"
              @input="smsForm.mobile = smsForm.mobile.replace(/\D/g, '')"
          />
        </el-form-item>
        <el-form-item label="验证码">
          <div class="code-input-group">
            <el-input
                v-model="smsForm.code"
                placeholder="请输入6位验证码"
                maxlength="6"
                @input="smsForm.code = smsForm.code.replace(/\D/g, '')"
            />
            <el-button
                type="text"
                :disabled="countdown > 0"
                @click="sendSmsCode"
                class="send-code-btn"
            >
              {{ countdown > 0 ? `${countdown}s后重发` : '获取验证码' }}
            </el-button>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="smsLogin">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import { ElMessage } from "element-plus";
import MD5 from 'md5';

export default {
  name: "Login",
  data() {
    return {
      currentTab: "password",
      form: { username: "", password: "" },
      smsForm: { mobile: "", code: "" },
      countdown: 0,
      timer: null
    };
  },
  methods: {
    // 新增：切换登录标签（仅控制显示，不影响你的方法）
    switchTab(tab) {
      this.currentTab = tab;
      // 切换时仅清空新增的smsForm，不碰你的form数据
      if (tab === 'sms') {
        this.smsForm = { mobile: "", code: "" };
      }
    },
    async login() {
      this.form.password = MD5(this.form.password)
      let { data: data } = await axios.post('http://localhost:8080/user/login', this.form)
      console.log(data)
      if (data.code == 200) {
        ElMessage.success(data.msg)
        sessionStorage.setItem("token", data.data)
        this.$router.push('/index')
      } else {
        ElMessage.error(data.msg)
      }
    },
    async sendSmsCode() {
      let { mobile } = this.smsForm;
      if (!mobile) {
        ElMessage.warning("请输入手机号");
        return;
      }
      if (!/^1[3-9]\d{9}$/.test(mobile)) {
        ElMessage.warning("请输入正确的手机号");
        return;
      }
        let { data:data } = await axios.post('http://localhost:8080/sendSmsCode', {
          mobile
        }, {
          headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        });
      console.log(data)
        if (data.code === 200) {
          ElMessage.success(data.msg);
          this.startCountdown();
        } else {
          ElMessage.error(data.msg);
        }
    },

    // 新增：倒计时（独立方法）
    startCountdown() {
      this.countdown = 60;
      this.timer = setInterval(() => {
        this.countdown--;
        if (this.countdown <= 0) {
          clearInterval(this.timer);
          this.timer = null;
        }
      }, 1000);
    },

    // 新增：手机号登录（独立方法，不影响你的逻辑）
    async smsLogin() {
      const { mobile, code } = this.smsForm;
      if (!mobile) {
        ElMessage.warning("请输入手机号");
        return;
      }
      if (!/^1[3-9]\d{9}$/.test(mobile)) {
        ElMessage.warning("请输入正确的手机号");
        return;
      }
      if (!code || code.length !== 6) {
        ElMessage.warning("请输入6位验证码");
        return;
      }
      const params = new URLSearchParams();
      params.append('mobile', this.mobile);
      params.append('code', this.code);
      let { data:data } = await axios.post('http://localhost:8080/user/smsLogin', params);
        if (data.code === 200) {
          ElMessage.success(data.msg);
          this.$router.push('/index');
        } else {
          ElMessage.error(data.msg);
        }
    }
  },

  // 新增：清除定时器（防止内存泄漏）
  beforeUnmount() {
    if (this.timer) {
      clearInterval(this.timer);
    }
  }
};
</script>

<style scoped>
/* 完全保留你的原有样式，仅新增切换标签和验证码相关样式 */
.login-page {
  width: 100vw;
  height: 100vh;
  position: relative;
}

.login-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #43cbff 0%, #9708cc 100%);
}

.login-card {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 400px;
  padding: 30px;
  background: #fff;
  border-radius: 10px;
}

.login-title {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
}

.login-form {
  margin-top: 20px;
}

/* 新增：登录方式切换标签样式 */
.login-tabs {
  display: flex;
  margin-bottom: 25px;
  border-bottom: 1px solid #eee;
}

.tab-item {
  padding: 8px 0;
  margin-right: 30px;
  font-size: 16px;
  color: #666;
  cursor: pointer;
  position: relative;
}

.tab-item.active {
  color: #43cbff;
  font-weight: 500;
}

.tab-item.active::after {
  content: "";
  position: absolute;
  bottom: -1px;
  left: 0;
  width: 100%;
  height: 2px;
  background: #43cbff;
}

/* 新增：验证码输入组样式 */
.code-input-group {
  display: flex;
  align-items: center;
}

.send-code-btn {
  color: #43cbff !important;
  padding: 0 10px !important;
}

.send-code-btn:disabled {
  color: #ccc !important;
  cursor: not-allowed;
}
</style>